<template>
  <div>
    <h2>申请者看到的流程列表</h2>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item el-form-item label="流程名称" prop="flowName">
        <el-input
          v-model="queryParams.flowName"
          placeholder="请输入流程名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入创建流程的用户名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程标识" prop="flowIden">
        <el-input
          v-model="queryParams.flowIden"
          placeholder="请输入流程的唯一标识"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="flowList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="流程名"
        align="center"
        key="flowInfo.name"
        prop="flowInfo.name"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="流程标识"
        align="center"
        key="flowInfo.flowIden"
        prop="flowInfo.flowIden"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="创建者"
        align="center"
        key="userName"
        prop="userName"
        v-if="columns[2].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="flowInfo.createTime"
        v-if="columns[3].visible"
        width="160"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.flowInfo.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleApply(scope.row)"
            >发起申请
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleLook(scope.row)"
            >流程详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 发起流程对话框 -->
    <el-dialog
      title="发起流程"
      :before-close="cancleApply"
      :visible.sync="applyDialog"
    >
      <div>
        <h1>{{ formInfo.formName }}</h1>
        <el-form label-position="top" label-width="80px">
          <div v-for="(item, index) in questions" :key="(item, index)">
            <el-form-item :label="index + 1 + '、' + item.questionName">
              <div v-if="item.questionType == 0">
                <el-input
                  v-model="answers[index].answer"
                  type="textarea"
                ></el-input>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleApply">取 消</el-button>
        <el-button type="primary" @click="submit">发 起</el-button>
      </span>
    </el-dialog>
    <!-- 查看流程详情对话框 -->
    <el-dialog title="流程详情" :visible.sync="nodesDialog">
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleLook">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
import {
  getNodes,
  getFormInfo,
  getFlowModel,
  submitFlow,
  listFlow,
  submitBlank,
} from "@/api/flow/flowlist";
//这里写页面的事务
export default {
  data() {
    return {
      // 总条数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      //流程列表
      flowList: [],
      //当前正在申请的流程id
      flowId: undefined,
      //填写表单对话框
      applyDialog: false,
      //节点信息对话框
      nodesDialog: false,
      //节点信息
      nodes: [],

      /** 表单 */
      //表单信息
      formInfo: {},
      //表单问题
      questions: [],
      //表单答案
      answers: [],

      /** 流程模型信息 */
      //流程基本信息
      flowInfo: {},
      //流程节点信息
      flowNodes: [],

      /** 流程实例化信息 */
      //流程实例
      flowInst: {},
      //流程实例节点
      flowNodesInst: [],

      //查询条件
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        flowName: undefined, //流程名
        userName: undefined, //用户名
        deptIds: [this.$store.state.user.deptid], //部门id数组
        flowIden: undefined, //流程英文标识
        flowStatus: true,
      },
      //时间范围
      dateRange: [],
      // 列信息
      columns: [
        { key: 0, label: `流程名`, visible: true },
        { key: 1, label: `流程标识`, visible: true },
        { key: 2, label: `创建者`, visible: true },
        { key: 3, label: `创建时间`, visible: true },
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询流程列表 */
    getList() {
      this.loading = true;
      listFlow(this.addDateRange1(this.queryParams, this.dateRange)).then(
        (response) => {
          console.log(response);
          this.flowList = response.flowInfo;
          this.total = response.counts;
          this.loading = false;
        }
      );
    },
    /** 发起申请按钮 */
    handleApply(row) {
      //当前正在申请的流程id
      this.flowId = row.flowInfo.id;
      //获取流程模型信息
      var params2 = {
        flowId: row.flowInfo.id,
      };
      console.log(row);
      getFlowModel(params2).then((response) => {
        console.log(response);
        //存储流程模型
        this.flowInfo = response.data.flowInfo;
        this.flowNodes = response.data.flowNodes;
        //根据流程模型创建流程实例和节点实例
        //创建流程实例
        this.flowInst = {
          id: nanoid(),
          name: this.flowInfo.name,
          formId: row.flowInfo.formId,
          flowId: this.flowId,
          currentOrder: 1,
          currentUserId: this.flowNodes[0].relatedUserId,
          userId: this.$store.state.user.id,
          status: 0,
          revies: false,
          createTime: null,
        };
        console.log("this.flowNodes");
        console.log(this.flowNodes);
        //创建节点实例
        for (var i = 0; i < this.flowNodes.length; i++) {
          var params = {
            id: nanoid(),
            name: this.flowNodes[i].name,
            flowInstId: this.flowInst.id,
            orderId: this.flowNodes[i].orderId,
            last: this.flowNodes[i].last,
            relatedUserId: this.flowNodes[i].relatedUserId,
            idea: "",
            sign: "",
            status: 0,
            time: null,
            ip: "",
          };
          //首节点状态置为开始
          if (i == 0) {
            params.status = 1;
          }
          this.flowNodesInst.push(params);
        }
        //获取业务表单基本信息、问题，创建答案数组
        var params1 = {
          formId: row.flowInfo.formId,
        };
        getFormInfo(params1).then((response) => {
          console.log(response);
          this.formInfo = response.data.form;
          this.questions = response.data.questionList;
          console.log(this.questions);
          for (var i = 0; i < this.questions.length; i++) {
            this.creatAnswer(this.questions[i]);
          }
        });
      });
      console.log("this.flowNodesInst");
      console.log(this.flowNodesInst);
      this.applyDialog = true;
    },
    /** 提交申请按钮 */
    submit() {
      //提交流程实例
      var params1 = {
        flowInst: this.flowInst,
        flowNodesInst: this.flowNodesInst,
      };
      submitFlow(params1).then((response) => {
        console.log(response);
      });
      console.log(this.questions);
      //提交业务表单
      for (var i = 0; i < this.answers.length; i++) {
        switch (this.questions[i].questionType) {
          case 0:
            var blank = {
              id: this.answers[i].id,
              userId: this.answers[i].userId,
              formId: this.answers[i].formId,
              questionId: this.answers[i].questionId,
              answer: this.answers[i].answer,
              creatTime: this.answers[i].creatTime,
              isSubmit: this.answers[i].isSubmit,
              flowInstId: this.answers[i].flowInstId,
              recordId: this.answers[i].recordId,
            };
            submitBlank(blank).then((response) => {
              console.log(response);
            });
            break;
        }
      }
      this.$message({
        message: "申请流程成功",
        type: "success",
      });
      this.reset();
      this.applyDialog = false;
    },
    creatAnswer(val) {
      switch (val.questionType) {
        case 0:
          var blank = {
            id: nanoid(),
            userId: this.$store.state.user.id,
            formId: val.formId,
            questionId: val.id,
            answer: "",
            creatTime: null,
            isSubmit: null,
            flowInstId: this.flowInst.id,
            recordId: null,
          };
          console.log(blank);
          console.log(this.flowInst);
          this.answers.push(blank);
          break;
      }
    },
    /** 取消申请按钮 */
    cancleApply() {
      this.applyDialog = false;
      this.reset();
    },
    /** 重置流程表单 */
    reset() {
      this.flowId = null;
      this.formInfo = {};
      this.questions = [];
      this.answers = [];
      this.flowInfo = {};
      this.flowNodes = [];
      this.flowInst = {};
      this.flowNodesInst = [];
    },
    /** 重置节点信息 */
    resetNodes() {
      this.nodes = [];
    },
    /** 查看节点详情 */
    handleLook(row) {
      var params = {
        flowId: row.id,
      };
      getNodes(params).then((response) => {
        this.nodes = response;
      });
      this.nodesDialog = true;
    },
    /** 关闭流程详情按钮 */
    cancleLook() {
      this.nodesDialog = false;
      this.resetNodes();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
  },
};
</script>
